﻿using NLua;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Reflection;

namespace ScriptEngine.Script.Extension
{
	public static class ScriptEngineHelper
	{
		/// <summary>
		/// 将枚举类型转化为对象
		/// </summary>
		/// <typeparam name="T">枚举泛型</typeparam>
		/// <param name="tEnum">枚举对象</param>
		/// <returns>转化后的对象</returns>
		public static IDictionary<string, object> EnumToObject<T>(T tEnum) where T : Enum
		{
			IDictionary<string, object> obj = new ExpandoObject();
			foreach (FieldInfo fieldInfo in tEnum.GetType().GetFields())
			{
				if (fieldInfo.Name == "value__") continue;
				long val = Convert.ToInt64(fieldInfo.GetValue(tEnum));
				obj.Add(fieldInfo.Name, val);
			}

			return obj;
		}

		/// <summary>
		/// 遍历表
		/// </summary>
		/// <param name="tab">luatable</param>
		/// <param name="iterator">迭代器</param>
		public static void ForEach(this LuaTable tab, Func<object, object, bool> iterator)
		{
			if (tab == null || iterator == null)
			{
				throw new NullReferenceException("table and iterator can't be null");
			}

			foreach (dynamic en in tab)
			{
				if (!iterator.Invoke(en.Key, en.Value))
				{
					break;
				}
			}
		}

		/// <summary>
		/// 以数组类型遍历表
		/// </summary>
		/// <param name="tab">luatable</param>
		/// <param name="iterator">迭代器</param>
		public static void ForEachAsArray(this LuaTable tab, Func<long, object, bool> iterator)
		{
			long index = 1;

			tab.ForEach((key, val) =>
			{
				if (key.GetType() != typeof(long))
				{
					return false;
				}

				if (((long)key) != index++)
				{
					return false;
				}

				return iterator((long)key, val);
			});
		}
	}
}
